package com.wstuo.configData.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;


import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.category.service.ICICategoryService;
import com.wstuo.common.config.category.service.IEventCategoryService;
import com.wstuo.common.config.customfilter.service.IFilterService;
import com.wstuo.common.config.dictionary.dao.IDataDictionaryItemsDAO;
import com.wstuo.common.config.dictionary.entity.DataDictionaryItems;
import com.wstuo.common.config.dictionary.service.IDataDictionaryGroupService;
import com.wstuo.common.config.dictionary.service.IDataDictionaryItemsService;
import com.wstuo.common.config.systeminfo.service.ISystemInfoService;
import com.wstuo.common.config.userCustom.service.IViewService;
import com.wstuo.common.noticeRule.entity.NoticeRule;
import com.wstuo.common.noticeRule.service.IEmailTemplateService;
import com.wstuo.common.noticeRule.service.INoticeRuleService;
import com.wstuo.common.rules.service.IRulePackageService;
import com.wstuo.common.rules.service.IRuleService;
import com.wstuo.common.scheduledTask.service.IScheduledTaskService;
import com.wstuo.common.sla.service.ISLAContractService;
import com.wstuo.common.tools.service.IAfficheService;
import com.wstuo.common.tools.util.ToolsUtils;

import com.wstuo.itsm.cim.dto.CIDTO;
import com.wstuo.itsm.cim.service.ICIService;
import com.wstuo.itsm.knowledge.service.IKnowledgeService;
import com.wstuo.common.config.moduleManage.entity.ModuleManage;
import com.wstuo.common.config.moduleManage.service.IModuleManageService;
import com.wstuo.itsm.updateRequest.service.IUpdateRequestService;
import com.wstuo.itsm.request.service.IRequestService;
import com.wstuo.common.bpm.service.IProcessUseService;
import com.wstuo.common.bpm.service.IFlowPropertyService;
import com.wstuo.common.bpm.api.IBPD;
import com.wstuo.common.bpm.dao.IProcessUseDAO;
import com.wstuo.common.bpm.dto.FlowActivityDTO;
import com.wstuo.common.bpm.dto.FlowPropertyDTO;
import com.wstuo.common.bpm.dto.ProcessUseDTO;
import com.wstuo.common.bpm.entity.ProcessUse;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.jbpm.FlowDesigner;
import com.wstuo.common.jbpm.IJbpmFacade;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.dto.UserDTO;
import com.wstuo.common.security.service.ICompanyService;
import com.wstuo.common.security.service.IFunctionService;
import com.wstuo.common.security.service.IOperationService;
import com.wstuo.common.security.service.IOrganizationService;
import com.wstuo.common.security.service.IRoleService;
import com.wstuo.common.security.service.IUserInfoService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.AppliactionBaseListener;
import com.wstuo.common.util.StringUtils;

/**
 * 基础配置数据加载Service类
 * @author will
 *
 */
public class ConfigDataLoaderService implements IConfigDataLoaderService{
	private static final String RULE_PATH =  AppConfigUtils.getInstance().getDroolsFilePath();
	final static Logger LOGGER = Logger.getLogger(ConfigDataLoaderService.class);
	private String languageVersion;
	@Autowired
	private IFunctionService functionService;//功能
	@Autowired
	private IOperationService operationService;//操作
	@Autowired
	private IUpdateRequestService updateRequestService;//升级默认数据
	@Autowired
	private IEventCategoryService eventCategoryService;//常用分类
	@Autowired
	private IDataDictionaryGroupService dataDictionaryGroupService;//数据字典分组
	@Autowired
	private IDataDictionaryItemsService dataDictionaryItemsService;//数据字典项
	@Autowired
    private IDataDictionaryItemsDAO dataDictionaryItemsDAO;//数据字典项
	@Autowired
	private ICompanyService companyService;//公司信息
	@Autowired
	private IOrganizationService organizationService;//机构信息（内部、服务机构）
	@Autowired
	private IRoleService roleService;//角色信息
	@Autowired
	private IUserInfoService userInfoService;//用户
	@Autowired
	private IRuleService ruleService;//请求规则
	@Autowired
	private ISLAContractService slaContractService;//SLA
	@Autowired
	private IJbpmFacade jbpmFacade;//流程
	@Autowired
    private IBPD bpd;
	@Autowired
	private IProcessUseService processUseService;//流程选用
	@Autowired
	private IRulePackageService rulePackageService;//流程选用
//	private IDashboardService dashboardService;//门户面板
	@Autowired
	private INoticeRuleService noticeService;
	@Autowired
	private IFlowPropertyService flowPropertyService;
	@Autowired
	private IKnowledgeService knowledgeService;
	@Autowired
	private ISystemInfoService systemInfoService;
	@Autowired
	private IScheduledTaskService scheduledTaskService;//定期任务
	@Autowired
	private IProcessUseDAO processUseDAO;
	@Autowired
	private IModuleManageService moduleManageService;
    @Autowired
    private IAfficheService afficheService;
	@Autowired
	private IFilterService filterService;
    @Autowired
    private IEmailTemplateService emailTemplateService;
	@Autowired
	private AppContext appctx;
	@Autowired
	private IViewService viewService;
	
	
	private String processKey;
	private String pid;
    private String deploymentId;
	public String getLanguageVersion() {
		return languageVersion;
	}
	public void setLanguageVersion(String languageVersion) {
		this.languageVersion = languageVersion;
	}
	/**
	 * 加载全部数据
	 * @param language
	 * @return String
	 */
	public String importAllConfigData(String language,Boolean hasDemoData){
		//加载基础文件
		preparingConfigure();
		languageVersion=language;
		//保存加载的时间或数据语言版本
		systemInfoService.initSystemInfoData(language);
		List<ModuleManage> lis=moduleManageService.findAll();
		String result="";
		try{
			functionService.importFunction(getFilePath("function.csv"));//功能
			operationService.importOperation(getFilePath("operation.csv"));//操作
			dataDictionaryGroupService.importDataDictionaryGroup(getImportFile("dictionary_group.csv"));//数据字典分组
			dataDictionaryItemsService.importDataDictionaryItems(getImportFile("dictionary_items.csv"));//数据字典项
			companyService.importCompanyInfo(getFilePath("company.csv"));//导入公司信息
			organizationService.importOrganization(getFilePath("organizations.csv"));//导入机构信息
			eventCategoryService.importEventCategory(getImportFile("category.csv"));//常用分类
			updateRequestService.saveUpdateRequest();//加载升级默认数据
			roleService.importRoleItems(getImportFile("roles.csv"));//导入角色
			roleService.importRoleResource(getImportFile("rolesResource.csv")); //导入角色权限
			ruleService.createDefalutRule();
			slaContractService.defaultSLAContract();
			userInfoService.importUserItems(getImportFile("users.csv"));//导入用户
			/*File folder = new File( RULE_PATH +"/change" );
	        //如果文件夹不存在就创建文件夹
	        if (!folder.exists()) {
	        	folder.mkdirs();
	        }*/
			for(ModuleManage mm:lis){
				if(mm.getModuleName().equals("request")){
					requestInstallData(hasDemoData);
				}
				/*if(mm.getModuleName().equals("problem")){
					problemInstallData(hasDemoData);
				}
				if(mm.getModuleName().equals("change")){
					changeInstallData(hasDemoData);
				}
				if(mm.getModuleName().equals("release")){
					releaseInstallData();
				}*/
				if(mm.getModuleName().equals("cim")){
					ciInstallData(hasDemoData);
				}
				
			}
			rulePackageService.printAllRuleFiles();//生成所有规则文件
			//dashboardService.importDashboard(getImportFile("dashboard.csv"));//门户面板

			filterService.importFilter();//请求过滤器 will
			filterService.importNewRequestFilter();//新建请求过滤器
			
			viewService.importViewData(getImportFile("view.csv"));
			//noticeService.importNotice(getImportFile("NoticeRuleTask.csv"));
			noticeService.importNotice(getImportFile("NoticeRule.csv"));
			
			//scheduledTaskService.importScheduledTask(getImportFile("ScheduledTask.csv"));
			
			if(hasDemoData){
				knowledgeService.importKnowledge(getImportFile("Knowledge.csv"));
				afficheInstallData();//scott
			}
			eventCategoryService.syncKnowledgeCategorys();
			eventCategoryService.syncRequestCategorys();//will
			result= "success";
		}catch(Exception ex){
			LOGGER.error(ex);
			result= "failure";
		}
		return result;
	}
	
	/**
	 * 多租户模式：加载基础数据
	 * @param language
	 * @return String
	 */
	public String importAllConfigData(String language,UserDTO userDTO){
		preparingConfigure();
		if(!StringUtils.hasText(language)){
			language = "cn";
		}
		languageVersion=language;
		//保存加载的时间或数据语言版本
		systemInfoService.initSystemInfoData(language);
		List<ModuleManage> lis=moduleManageService.findAll();
		String result="";
		try{
			functionService.importFunction(getFilePath("function.csv"));//功能
			operationService.importOperation(getFilePath("operation.csv"));//操作
			
			dataDictionaryGroupService.importDataDictionaryGroup(getImportFile("dictionary_group.csv"));//数据字典分组
			dataDictionaryItemsService.importDataDictionaryItems(getImportFile("dictionary_items.csv"));//数据字典项
			companyService.importCompanyInfo(getFilePath("company.csv"));//导入公司信息
			organizationService.importOrganization(getFilePath("organizations.csv"));//导入机构信息
			
			eventCategoryService.importEventCategory(getImportFile("category.csv"));//常用分类
			updateRequestService.saveUpdateRequest();//加载升级默认数据
			roleService.importRoleItems(getImportFile("roles.csv"));//导入角色
			roleService.importRoleResource(getImportFile("rolesResource.csv")); //导入角色权限

			ruleService.createDefalutRule();
			slaContractService.defaultSLAContract();
			//userInfoService.importUserItems(getImportFile("users.csv"));//导入用户
			userInfoService.createTenantUser(userDTO);
			for(ModuleManage mm:lis){
				if(mm.getModuleName().equals("request")){
					requestInstallData(false);
				}
				/*if(mm.getModuleName().equals("problem")){
					problemInstallData(false);
				}
				if(mm.getModuleName().equals("change")){
					changeInstallData(false);
				}
				if(mm.getModuleName().equals("release")){
					releaseInstallData();
				}*/
				if(mm.getModuleName().equals("cim")){
					//ciInstallData(false);
				}
				
			}
			rulePackageService.printAllRuleFiles();//生成所有规则文件

			//Long filterId = filterService.importFilter();//请求过滤器 will
			filterService.importNewRequestFilter();//新建请求过滤器
			//noticeService.importNotice(getImportFile("NoticeRuleTask.csv"));
			noticeService.importNotice(getImportFile("NoticeRule.csv"));
			
			//scheduledTaskService.importScheduledTask(getImportFile("ScheduledTask.csv"));
			
			eventCategoryService.syncKnowledgeCategorys();
			eventCategoryService.syncRequestCategorys();//will
			result= "success";
			
		}catch(Exception ex){
			LOGGER.error(ex);
			result= "failure";
		}
		return result;
	}
	
	/**
	 * 加载请求演示数据
	 */
	@Transactional
	private void requestInstallDemoData(){
		
		ApplicationContext ctx=AppliactionBaseListener.ctx;
		IRequestService requestService=(IRequestService)ctx.getBean("requestService");
		requestService.importRequest(getImportFile("Request.csv"));
	}
	/**
	 * 加载问题演示数据
	 */
	@Transactional
	private void problemInstallDemoData(){
		/*ApplicationContext ctx=AppliactionBaseListener.ctx;
		IProblemService problemService=(IProblemService)ctx.getBean("problemService");
		problemService.importProblem(getImportFile("Problem.csv"));*/
	}
	/**
	 * 加载变更演示数据
	 */
	@Transactional
	private void changeInstallDemoData(){
		/*ApplicationContext ctx=AppliactionBaseListener.ctx;
		IChangeService changeService=(IChangeService)ctx.getBean("changeService");
		changeService.importChange(getImportFile("Change.csv"));*/
	}
	/**
	 * 加载配置项演示数据
	 */
	@Transactional
	private void ciInstallDemoData(){
		ApplicationContext ctx=AppliactionBaseListener.ctx;
		ICIService ciService=(ICIService)ctx.getBean("ciService");
		CIDTO cidto = new CIDTO();
        cidto.setCompanyNo(1L);
		ciService.importCI(getImportFile("ConfigureItem.csv"), cidto);
	}
	/**
	 * 模块数据加载公共方法
	 * @param module
	 * @param isHaveProcess
	 * @param isHaveNotice
	 */
	public void moduleInstallDataCommon(String Language,String module,Boolean isHaveProcess,Boolean isHaveNotice){
		languageVersion=Language;
		try{
			dataDictionaryGroupService.importDataDictionaryGroup(getImportFile(module+"/status_Group.csv"));//数据字典分组
			dataDictionaryItemsService.importDataDictionaryItems(getImportFile(module+"/status.csv"));//数据字典项
			if(isHaveProcess){
				String deployUrl =FlowDesigner.PROCESS_FILE_PATH+"/result.jpdl.xml";
		    	File jpdlRawFile = new File(deployUrl);
		    	String strResult = bpd.deployProcessDefinitionXmlFile(jpdlRawFile);

		    	strResult = flowPropertyService.findFlowPropertyByDeploymentId(strResult);
				//通过读取processSetting文件来获取当前模块流程的ProcessKey和ProcessDefinitionId
		    	/*processKey=line[0].toString();
				pid=line[1].toString();*/
				//processUserCommon(module,"request_default","request_default-1");
			}
			if(isHaveNotice){
				noticeService.importNotice(getImportFile(module+"/noticeRule.csv"));
			}
		}catch (Exception e) {
			LOGGER.error(e);
		}
		
	}
	/**
	 * 获取加载模块的PrcessKey和Id
	 * @param module
	 */
	public void getProcessKeyAndId(String module){
		try{
			Reader rd = new InputStreamReader(new FileInputStream(getImportFile(module+"/processSetting.csv")),"UTF-8");//以字节流方式读取数据
			CSVReader reader=new CSVReader(rd);
			String[] line=reader.readNext();
			processKey=line[0].toString();
			pid=line[1].toString();
		}catch (Exception e) {
			LOGGER.error(e);
		}
	}
	/**
	 * 加载流程公共方法
	 * @param module
	 */
	public void loadBpm(String module){
		deploymentId=jbpmFacade.deployJpdl(getImportFile(module+"/itil-process.zip"));//流程
	}
	/**
	 *  请求加载基础数据
	 * @param mm
	 * @param hasDemoData
	 */
	private void requestInstallData(Boolean hasDemoData){
		try{
			eventCategoryService.importEventCategory(getImportFile("request/category.csv"));//常用分类
			moduleInstallDataCommon(languageVersion,"request",true,true);
			//requestPreceeDefaultSet();
			if(hasDemoData){
				requestInstallDemoData();
			}
		}catch (Exception e) {
			LOGGER.error(e);
			e.printStackTrace();
		}
		
	}
	/**
	 * 配置项加载基础数据
	 * @param mm
	 * @param hasDemoData
	 */
	private void ciInstallData(Boolean hasDemoData){
		try{
			ApplicationContext ctx=AppliactionBaseListener.ctx;
			ICICategoryService cicategoryService=(ICICategoryService)ctx.getBean("cicategoryService");
			cicategoryService.importCiCategory(getImportFile("cim/category.csv"));//配置项分类
			moduleInstallDataCommon(languageVersion,"cim",false,true);
			if(hasDemoData){
				ciInstallDemoData();
			}
		}catch (Exception e) {
			LOGGER.error(e);
		}
	}
	/**
	 *  问题加载基础数据
	 * @param mm
	 * @param hasDemoData
	 */
	private void problemInstallData(Boolean hasDemoData){
		try{
			eventCategoryService.importEventCategory(getImportFile("problem/category.csv"));//常用分类
			moduleInstallDataCommon(languageVersion,"problem",true,true);
			problemPreceeDefaultSet();
			if(hasDemoData){
				problemInstallDemoData();
			}
		}catch (Exception e) {
			LOGGER.error(e);
		}
	}
	/**
	 * 变更加载基础数据
	 * @param mm
	 * @param hasDemoData
	 */
	private void changeInstallData(Boolean hasDemoData){
		try{
			eventCategoryService.importEventCategory(getImportFile("change/category.csv"));//常用分类
			moduleInstallDataCommon(languageVersion,"change",true,true);
			changePreceeDefaultSet();
			if(hasDemoData){
				changeInstallDemoData();
			}
		}catch (Exception e) {
			LOGGER.error(e);
		}
		
	}
	/**
	 * 发布加载基础数据
	 * @param mm
	 */
	private void releaseInstallData(){
		try{
			eventCategoryService.importEventCategory(getImportFile("release/category.csv"));//常用分类
			moduleInstallDataCommon(languageVersion,"release",true,true);
			releasePreceeDefaultSet();
		}catch (Exception e) {
			LOGGER.error(e);
		}
	}
	  /**
	   * 公共方法，取得CSV文件路径.
	   * @param fileName 
	   * @return csvFilePath String
	   */
	  public String getFilePath(String fileName){
		  return ServletActionContext.getServletContext().getRealPath("")+"/configData/"+languageVersion+"/"+fileName;
	  } 
	  
	  /**
	   * 公共方法，取得CSV文件.
	   * @param fileName
	   * @return csvFile File
	   */
	  public File getImportFile(String fileName){
		  return new File(getFilePath(fileName));
	  }
	  /**
		 * 加载使用流程
		 * @param module
		 * @param processKey
		 * @param pid
		 */
	  @Transactional
	  public void processUserCommon(String module,String processKey,String pid){
		  ProcessUse processUse=processUseDAO.findUniqueBy("useName", "processUse");
		  ProcessUseDTO dto=new ProcessUseDTO();
		  entity2dto(processUse,dto);
		  if(module.equals("request")){
			  dto.setRequestProcessKey(processKey);
			  dto.setRequestProcessDefinitionId(pid);
		  }else if(module.equals("problem")){
			  dto.setProblemProcessKey(processKey);
			  dto.setProblemProcessDefinitionId(pid);
		  }else if(module.equals("change")){
			  dto.setChangeProcessKey(processKey);
			  dto.setChangeProcessDefinitionId(pid);
		  }else{
			  dto.setReleaseProcessKey(processKey);
			  dto.setReleaseProcessDefinitionId(pid);
		  }
		  
		  dto.setUseName("processUse");
		  processUseService.processUseSave(dto);
	  }
	 /**
	  * 请求默认流程
	  */
	  private void requestPreceeDefaultSet(){
/*		  String requestPid = "wstuo_request-1";
		  if("en".equals(languageVersion)){
			  requestPid ="wstuo_request_en_1-1";
		  }else if("jp".equals(languageVersion)){
			  requestPid ="wstuo_request_jp_1-1";
		  }else if("tw".equals(languageVersion)){
			  requestPid ="wstuo_request_tw_1-1";
		  }else{
			  requestPid ="wstuo_request-1";
		  }
		  
		  System.err.println(requestPid+"===================33");*/
		  //请求
		  String deploymentIds=deploymentId;
		  String[] statusCode = new String[]{"request_approval","request_one","request_two","request_three","request_four","request_complete","request_closeApprove"};
		  String result = flowPropertyService.findFlowPropertyByDeploymentId(deploymentIds);
		 /* if(fpDto!=null && fpDto.getFlowActivityDTO()!=null){
			  int i = 0;
			  List<OrganizationDTO> orgs =  organizationService.findAllOrganization();
			  for(FlowActivityDTO dto : fpDto.getFlowActivityDTO()){
				  if(FlowActivityDTO.TaskActivityType.equals(dto.getActivityType())){
					  dto.setDynamicAssignee(true);
					  DataDictionaryItems di = dataDictionaryItemsDAO.findUniqueBy("dno", statusCode[i]);
					  dto.setStatusNo(di.getDcode());
					  NoticeRule noticeRule = noticeService.findEntityByNoticeNo(INoticeRuleService.REQUEST_FLOW_ACTION_NOTICE);
					  dto.setNoticeRuleId(noticeRule.getNoticeRuleId());
					  dto.setNoticeRuleIds(noticeRule.getNoticeRuleId().toString());
					  dto.setNoticeRule(noticeRule.getNoticeRuleName());
					  if(i==3){
						  dto.setValidMethod("SolutionsNotEmptyValidate");
					  }
					  if(i==4){
						  dto.setAssignType("autoAssignee");
						  dto.setAllowUdateDefaultAssignee(true);
						  dto.setIsUpdateEventAssign(true);
					  }else{
						  dto.setAssignType("autoAssignee");
					  }
					  if(orgs!=null && orgs.size()>0){
						  dto.setCandidateGroupsNo(orgs.get(0).getOrgNo().toString());
						  dto.setCandidateGroupsName(orgs.get(0).getOrgName());
					  }
					  flowPropertyService.updateFlowActivity(dto);
					  i++;
				  }
			  }
		  }*/
	  }
	  /**
	   * 问题默认流程
	   */
	  private void problemPreceeDefaultSet(){
		  String problemPid = "itil_problem_2_1-1";
		  if("en".equals(languageVersion)){
			  problemPid="itil_problem_en_2_1-1";
			}else if("jp".equals(languageVersion)){
				problemPid="itil_problem_jp_2_1-1";
			}else if("tw".equals(languageVersion)){
				problemPid="itil_problem_tw_2_1-1";
			}else{
				problemPid="itil_problem_2_1-1";
			}
		  //问题
		  String[] statusCode1 = new String[]{"problem_analyze","problem_resolve","problem_submitApproval","problem_approvalPass"};
		  FlowPropertyDTO fpDto1 = flowPropertyService.findFlowPropertyByProcessDefinitionId(problemPid);
		  if(fpDto1!=null && fpDto1.getFlowActivityDTO()!=null){
			  int i = 0;
			  List<OrganizationDTO> orgs =  organizationService.findAllOrganization();
			  for(FlowActivityDTO dto : fpDto1.getFlowActivityDTO()){
				  if(FlowActivityDTO.TaskActivityType.equals(dto.getActivityType())){
					  dto.setDynamicAssignee(true);
					  DataDictionaryItems di = dataDictionaryItemsDAO.findUniqueBy("dno", statusCode1[i]);
					  dto.setStatusNo(di.getDcode());
					  NoticeRule noticeRule = noticeService.findEntityByNoticeNo(INoticeRuleService.PROBLEM_FLOWACTION_NOTICE);
					  dto.setNoticeRuleId(noticeRule.getNoticeRuleId());
					  dto.setNoticeRuleIds(noticeRule.getNoticeRuleId().toString());
					  dto.setNoticeRule(noticeRule.getNoticeRuleName());
					  if(i==2){
						  dto.setAssignType("autoAssignee");
						  dto.setAllowUdateDefaultAssignee(true);
						  dto.setIsUpdateEventAssign(true);
						  dto.setValidMethod("ProblemSolutionsNotEmptyValidate");
					  }else{
						  dto.setAssignType("autoAssignee");
					  }
					  if(orgs!=null && orgs.size()>0){
						  dto.setCandidateGroupsNo(orgs.get(0).getOrgNo().toString());
						  dto.setCandidateGroupsName(orgs.get(0).getOrgName());
					  }
					  flowPropertyService.updateFlowActivity(dto);
					  i++;
				  }
			  }
		  }
	  }
	  /**
	   * 变更默认流程
	   */
	  private void changePreceeDefaultSet(){
		  String changePid = "itil_change_2_1-1";
		  if("en".equals(languageVersion)){
			  changePid="itil_change_en_2_1-1";
			}else if("jp".equals(languageVersion)){
				changePid="itil_change_jp_2_1-1";
			}else if("tw".equals(languageVersion)){
				changePid="itil_change_tw_2_1-1";
			}else{
				changePid="itil_change_2_1-1";
			}
		  //变更
		  String[] statusCode2 = new String[]{"change_plan","","change_approval","change_implement","change_review","change_close"};
		  FlowPropertyDTO fpDto2 = flowPropertyService.findFlowPropertyByProcessDefinitionId(changePid);
		  if(fpDto2!=null && fpDto2.getFlowActivityDTO()!=null){
			  int i = 0;
			  List<OrganizationDTO> orgs =  organizationService.findAllOrganization();
			  for(FlowActivityDTO dto : fpDto2.getFlowActivityDTO()){
				  if(FlowActivityDTO.TaskActivityType.equals(dto.getActivityType()) || "foreach".equals(dto.getActivityType())){
					  dto.setDynamicAssignee(true);
					  DataDictionaryItems di = dataDictionaryItemsDAO.findUniqueBy("dno", statusCode2[i]);
					  NoticeRule noticeRule = noticeService.findEntityByNoticeNo(INoticeRuleService.CHANGE_FLOW_ACTION_NOTICE);
					  dto.setNoticeRuleId(noticeRule.getNoticeRuleId());
					  dto.setNoticeRuleIds(noticeRule.getNoticeRuleId().toString());
					  dto.setNoticeRule(noticeRule.getNoticeRuleName());
					  if(di!=null){
						  dto.setStatusNo(di.getDcode());
					  }
					  if(i==2){
						  dto.setApproverTask(true);
					  }
					  dto.setAssignType("autoAssignee");
					  if(orgs!=null && orgs.size()>0){
						  dto.setCandidateGroupsNo(orgs.get(0).getOrgNo().toString());
						  dto.setCandidateGroupsName(orgs.get(0).getOrgName());
					  }
					  flowPropertyService.updateFlowActivity(dto);
					  i++;
				  }
			  }
		  }
	  }
	  /**
	   * 发布默认流程
	   */
	  private void releasePreceeDefaultSet(){
		  String releasePid = "itil_release_cn_1_1-1";
		  if("en".equals(languageVersion)){
			  releasePid="itil_release_en_1_1-1";
			}else if("jp".equals(languageVersion)){
				releasePid="itil_release_jp_1_1-1";
			}else if("tw".equals(languageVersion)){
				releasePid="itil_release_tw_1_1-1";
			}else{
				releasePid="itil_release_cn_1_1-1";
			}
		  //发布
		  String[] statusCode2 = new String[]{"release_plan","release_managerApproval","release_build","release_changeProcess","release_implementCheck","release_updateCMDB","release_complete"};
		  FlowPropertyDTO fpDto2 = flowPropertyService.findFlowPropertyByProcessDefinitionId(releasePid);
		  if(fpDto2!=null && fpDto2.getFlowActivityDTO()!=null){
			  int i = 0;
			  List<OrganizationDTO> orgs =  organizationService.findAllOrganization();
			  for(FlowActivityDTO dto : fpDto2.getFlowActivityDTO()){
				  if(FlowActivityDTO.TaskActivityType.equals(dto.getActivityType()) || "foreach".equals(dto.getActivityType())){
					  dto.setDynamicAssignee(true);
					  DataDictionaryItems di = dataDictionaryItemsDAO.findUniqueBy("dno", statusCode2[i]);
					  NoticeRule noticeRule = noticeService.findEntityByNoticeNo(INoticeRuleService.RELEASE_FLOW_ACTION_NOTICE);
					  dto.setNoticeRuleId(noticeRule.getNoticeRuleId());
					  dto.setNoticeRuleIds(noticeRule.getNoticeRuleId().toString());
					  dto.setNoticeRule(noticeRule.getNoticeRuleName());
					  if(di!=null){
						  dto.setStatusNo(di.getDcode());
					  }
					  dto.setAssignType("autoAssignee");
					  if(orgs!=null && orgs.size()>0){
						  dto.setCandidateGroupsNo(orgs.get(0).getOrgNo().toString());
						  dto.setCandidateGroupsName(orgs.get(0).getOrgName());
					  }
					  flowPropertyService.updateFlowActivity(dto);
					  i++;
				  }
			  }
		  }
	  }
	  

	 /* *//**
	   * 加载月份和星期默认值
	   *//*
	  @Transactional
	  private void insertMonthWeekDefault(){
		  for(Long i=1L;i<=12;i++){
			  Months m = new Months();
			  m.setMonths(i);
			  System.out.println("---------Months--------"+i);
			  monthsDAO.merge(m);
		  }
		  for(Long i=1L;i<=7;i++){
			  Weeks w = new Weeks();
			  w.setWeeks(i);
			  System.out.println("---------Weeks--------"+i);
			  weeksDAO.merge(w);
		  }
	  }*/
	  /**
	   * 实体转ＤＴＯ
	   * @param entity
	   * @param dto
	   */
	  private void entity2dto(ProcessUse entity,ProcessUseDTO dto){
		  if(entity!=null){
			  dto.setProcessUseNo(entity.getProcessUseNo());
			  dto.setChangeProcessDefinitionId(entity.getChangeProcessDefinitionId());
			  dto.setChangeProcessKey(entity.getChangeProcessKey());
			  dto.setProblemProcessDefinitionId(entity.getProblemProcessDefinitionId());
			  dto.setProblemProcessKey(entity.getProblemProcessKey());
			  dto.setRequestProcessDefinitionId(entity.getRequestProcessDefinitionId());
			  dto.setRequestProcessKey(entity.getRequestProcessKey());
			  dto.setReleaseProcessDefinitionId(entity.getReleaseProcessDefinitionId());
			  dto.setReleaseProcessKey(entity.getReleaseProcessKey());
		  }
	  }
	  
	  /**
	   * 装在公告数据；
	   */
	  private void afficheInstallData(){
		  afficheService.importAffiche(getImportFile("affiche.csv"));
	  }
	  /**
	   * 准备配置文件
	   */
	  public String preparingConfigure(){
		  String filepath=AppConfigUtils.getInstance().getFileManagementPath()+appctx.getCurrentTenantId()+"/";
		  File upload = new File(filepath+"/images");//上传图片的位置
		  upload.mkdirs();
		  
		  //请求规则的位置
		  File request = new File(filepath+"/drools/drl/request");
		  request.mkdirs();
		  //请求邮件规则的位置
		  File requestMail = new File(filepath+"/drools/drl/requestMail");
		  requestMail.mkdir();
		  //请求流程规则的位置
		  File requestWorkFlow = new File(filepath+"/drools/drl/requestWorkFlow");
		  //变更流程规则的位置
		  //File changeWorkFlow = new File(filepath+"/drools/drl/changeWorkFlow");
		  requestWorkFlow.mkdir();
		  //请求SLA规则的位置
		  File sla = new File(filepath+"/drools/drl/sla");
		  sla.mkdir();
		  //附件的位置
		  File attachments = new File(filepath+"/attachments");
		  attachments.mkdir();
		  //导出文件位置
		  File exportFile = new File(filepath+"/exportFile");
		  exportFile.mkdir();
		  //用户在线日志文件位置
		  File onlineLog = new File(filepath+"/log/onlineLog");
		  onlineLog.mkdir();
		  //用户操作日志文件位置
		  File optLog = new File(filepath+"/log/optLog");
		  optLog.mkdir();
		  //错误日志文件位置
		  File errLog = new File(filepath+"/log/errorLog");
		  errLog.mkdir();
		  //二维码文件位置
		 /* File qrCode = new File(filepath+"/QRCodePath");
		  qrCode.mkdir();*/
		  //邮件模版copy
		  String destDir = filepath + IEmailTemplateService.TEMPLATEDIRNAME;
		  emailTemplateService.copyEmailTemplate(destDir);
		  //各公司预设logo的copy
		  //reportLogoCopy();
		  companyLogoCopy();
		  return "";
	  }
	  /**
	   * copy report logo
	   */
	  private void reportLogoCopy(){
		  File inputlogoFile = new File(AppConfigUtils.getInstance().getReportRoot()+"/logo.jpg");
          File outputlogoFile=new File(AppConfigUtils.getInstance().getFileManagementPath()+appctx.getCurrentTenantId()+"/jasper/logo.jpg");
          ToolsUtils.copy( inputlogoFile,outputlogoFile);
	  }
	  /**
	   * copy report logo
	   */
	  private void companyLogoCopy(){
		  File inputlogoFile = new File(ServletActionContext.getServletContext().getRealPath("upload")+"/images/logo.png");
          File outputlogoFile = new File(AppConfigUtils.getInstance().getFileManagementPath()+appctx.getCurrentTenantId()+"/images/logo.png");
          ToolsUtils.copy( inputlogoFile,outputlogoFile);
	  }
}
